<template>
  <div class="body">
  <div class="affix">
    <el-affix :offset="30">
      <el-dropdown @command="handleCommand" size="large">
          <span class="el-dropdown-link">
              关联知识点
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
          </span>
          <template #dropdown>
          <el-dropdown-menu>
              <el-dropdown-item command="1">信息技术</el-dropdown-item>
              <el-dropdown-item command="2">通用技术</el-dropdown-item>
              <el-dropdown-item command="3">职高计算机</el-dropdown-item>
          </el-dropdown-menu>
          </template>
      </el-dropdown>
      <div class="knowledgepointList" v-show="showKnowledgepointList">
        <el-button
          v-for="item in state.knowledgepointList"
          :key="item.name"
          :type="getButtonType(item.id)"
          text
          size="small"
          @click="linkKnowledgeClick(item.id,item.name)"
          >{{ item.name }}
        </el-button>
        <el-button
          text
          size="small"
          @click="hideKnowledgepointList"
        >关闭知识点</el-button>
      </div>
    </el-affix>
</div>

  <el-drawer v-model="state.showDrawer" title="试卷题目录入说明" size="'70%'">
      <template #header>
        <h4>试卷题目录入说明</h4>
      </template>
      <template #default>
        <img src="../assets/lurushuoming.png" />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="warning" @click="state.showDrawer=false">取消</el-button>    
        </div>
      </template>
    </el-drawer>
    <div class="download">
      <div class="downloadHeader">
        <el-button type="primary" text @click="DownloadFile()">
          试卷模板下载<el-icon class="el-icon--right"><Download /></el-icon>
        </el-button>
        <el-button type="primary" text @click="showHelpDocument()">
          查看说明<el-icon class="el-icon--right"><Document /></el-icon>
        </el-button>
      </div>
      <el-upload
        ref="uploadFileRef"
        :name=state.upload_file
        :headers="{
          token: state.token
        }"
        class="upload-demo"
        drag
        :file-list="fileList"
        :action="state.uploadPaperFileServer"
        accept=".docx"
        :multiple="false"
        :show-file-list="true"
        :on-success="handleSuccess"
        :on-error="handleError"
        :auto-upload="true"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
                文件拖拽这里或 <em>点击上传</em>
          </div>
        <template #tip>
          <div class="el-upload__tip">
            注意:只能上传docx文件,且文件大小不超过8MB
          </div>
        </template>
      </el-upload>
    </div>
  
  <div class="paper_info" v-if="state.paperInforVisible">
    <h1>校对试卷信息</h1>
    <el-form
      ref="ruleFormRef"
      :model="state.paperInformation"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="state.paperInformation.title"/>
        <el-button type="primary" @click="VerifyPaperTitle()">标题查重</el-button>
      </el-form-item> 
      <el-form-item label="发布日期" prop="publish_time">
        <el-input v-model="state.paperInformation.publish_time"/>
      </el-form-item>
    
      <el-form-item label="开放" prop="open_level">
        <el-radio-group v-model="state.paperInformation.open_level">
          <el-radio label="public" >公开</el-radio>
          <el-radio label="private" >私有</el-radio>
          <el-radio label="friend" disabled>好友可见</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="年级" prop="grade">       
        <el-radio-group v-model="state.paperInformation.grade">
          <el-radio label="3" >高三</el-radio>
          <el-radio label="2" >高二</el-radio>
          <el-radio label="1" disabled>高一</el-radio>
        </el-radio-group>
      </el-form-item> 
      
      <el-form-item label="类型" prop="is_joint">
        <el-switch
          v-model="state.paperInformation.is_joint"
          class="mb-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;"
          active-text= "联考卷"
          inactive-text= "原创/改编卷"
          active-value = 'true'
          inactive-value = 'false'
          @change="handleSwithChange()"          
        />
      </el-form-item>
    </el-form>
  </div>
  <h1>校对试题</h1>
  <div>
      <el-card class="box-card" v-for="(item, index) in state.returnQuestionList" :key="index"
        shadow="hover"
        :class="{active:state.selectIndex==index}"
        @click="selectCardClick(index)"
      >
          <template #header>
            <div class="card-header">
              <el-button type="danger" :icon="Delete" circle @click="onClickClearKnowledge(index)" />
              <span>题号：{{ item.order }} </span>
              <span>知识点：
                <block v-for="(item, index) in item.knowledgepoint_cn" :key="index">
                  {{ item }};
                </block>                
              </span>
              <span>题型：{{item.type_cn}}</span>
              <!-- <el-row>
                <span>难度</span>
                <el-rate v-model="item.difficulty_level" disabled/>
              </el-row> -->
              <!-- <span>日期：{{ item.publish_time }}</span>
              <span>来源：{{ item.reference }}</span>     -->
              <el-button :icon="EditPen" size="small" @click="editeOneQuestionClick(item,index)" ></el-button>
              <el-button :icon="Plus" size="small" @click="addOneQuestionClick(item,index)" ></el-button>
              <el-button :icon="Delete" size="small" @click="deleteOneQuestionClick(index)" ></el-button>        
            </div>
        </template>
        <div class="card-body">           
            <div v-html="item.content" class="line-break"></div>
            <!-- <el-image v-for="url in item.images" :key="url" :src="url" style="width: 150px;height: 100px;" />   -->
            <p>【答案】</p>
            <div v-html="item.answer" class="line-break"></div>
             <p>【解析】</p>
            <div v-html="item.explain" class="line-break"></div>
            <!-- <el-image v-for="url in item.images_explain" :key="url" :src="url" style="width: 150px;height: 100px;" />   -->
    
        </div>
      </el-card>
  </div> 
  <EditeOneQuestionDialoge ref="editeOneQuestionDialoge" :type="state.type" :question="state.question" :father_method="updateQuestionList" />
  <!-- <AddQuestionDialoge ref="addQuestionDialoge" :type="state.type" :knowledgepointId=state.knowledgepointId :recoverQuestionList="recoverQuestionList" />     -->
  <div>   
    <el-button 
      type="success" 
      @click="commitClick()" 
      :disabled="state.buttonDisabeled"
      v-loading="state.loading"
      element-loading-text="试卷正在提交，请耐心等待5s..."
      >提交到数据库
    </el-button>
  </div>

</div>
</template>
  
<script setup>
  import { reactive, ref, toRaw, onMounted, onUnmounted, } from 'vue'
  import { EditPen,Document, Download,View, ArrowDown, Plus,Delete, Picture } from '@element-plus/icons-vue'
  import { localGet, uploadPaperFileServer, deepClone,convertQuestionFormat,deleteQuestionItem} from '@/utils'
  import EditeOneQuestionDialoge from '@/views/EditeOneQuestionDialoge.vue'
  import AddQuestionDialoge from '@/views/AddQuestionDialoge.vue'
  import { useRouter, useRoute } from 'vue-router'
  import { useStore } from 'vuex'
  import axios from 'axios'
  import { ElMessage, resultProps, ElMessageBox } from 'element-plus'  

  const showKnowledgepointList = ref(false)
  const editeOneQuestionDialoge = ref()
  const ruleFormRef = ref(null)
  const store=useStore()
  const uploadFileRef = ref(null)
  const fileList = ref([])
  const route = useRoute()
  const router = useRouter()
  const formSize = ref('default')
  const addQuestionDialoge=ref(null) //引入修改题目弹窗组件
  const buttonTypeList = ['primary', 'success', 'info', 'warning', 'danger']
  const getButtonType =(value)=>{    
    return buttonTypeList[value % buttonTypeList.length]
  }
  const subjectOptions = [
  {
    value: 1,
    label: '信息技术',
  },
  {
    value: 2,
    label: '通用技术',
  },
  {
    value: 3,
    label: '职高计算机',
  },
]
  const state = reactive({
    upload_file: 'upload_file',
    loading:false,
    apiName:"",
    paperId:0,
    selectQuestionId:0,
    subjectId: 0,
    knowledgepointList:null,
    showKnowledgepointList:false,
    selectIndex:-1,
    paperInforVisible:true,
    token:localGet('token') || "",
    uploadPaperFileServer,
    returnQuestionList: null,
    selectedQuestion: Object,
    buttonDisabeled: true,
    dialogVisible: false,
    index:Number,
    type:"edit",
    knowledgepointId:-1,
    showDrawer: false,
    paperInformation:{
      title:"",
      publish_time:"",
      is_joint:'true',
      open_level:'public',
      grade:'3',
    },
    importType:'',
  })
  // 清空所选的某个题目的关联知识点
  const onClickClearKnowledge = (index) =>{
    console.log('未清理前知识点id:',state.returnQuestionList[index].knowledgepoint)
    console.log('未清理前知识点中文:',state.returnQuestionList[index].knowledgepoint_cn)
    state.returnQuestionList[index].knowledgepoint=[]
    state.returnQuestionList[index].knowledgepoint_cn=[]
    console.log('清理后知识点id:',state.returnQuestionList[index].knowledgepoint)
    console.log('清理后知识点中文:',state.returnQuestionList[index].knowledgepoint_cn)
  }
  // 隐藏知识点列表
  const hideKnowledgepointList = () => {
    showKnowledgepointList.value = false
  }
  // 更新题目
  const updateQuestionList=(list_index,question)=>{
    console.log('题目index',list_index,question)
    state.returnQuestionList[list_index]=deepClone(question)
    console.log('所有题目：',state.returnQuestionList)
  }
  onMounted(()=>{
    console.log("我要监视路由")
    const {id, importQuestionType, subject, is_answer_detach} = route.query
    // 根据学科，设置不同的upload上传参数和接口不一样，用于后台判断不同的学科，主要是职高计算机有特殊性
    if(subject==='vocational'){
      state.upload_file = 'upload_file_vocational'
    }else{
      if (is_answer_detach === 'true'){
        state.upload_file = 'upload_file_detach'
      } else {
        state.upload_file = 'upload_file'
      }      
    }
    // 根据导入题目类型不同，设置相应的接口和参数
    if(importQuestionType=="importQuestionsSupplementPaper"){
      if(id>0){
        state.paperId=id
        state.paperInforVisible=false
        state.apiName='/GeneratePaper2Database/'
        state.importType=importQuestionType
      }else{
        ElMessage.error("路由参数错误，必须携带paperId")
        // return false;
      }
    }else
    if(importQuestionType=="JustImportQuestions"){
      state.paperInforVisible=false;
      state.apiName="/PersistenceManyQuestions2DatabaseAPIView/"
      state.importType=importQuestionType
    }else
    if(importQuestionType=='importQuestionsAndPaper'){
      state.paperInforVisible=true;
      state.apiName='/GeneratePaper2Database/'
      state.importType=importQuestionType
    }else{
      ElMessage.error("路由参数错误，必须携带type正确值")
      // return false;
    }
    console.log('监视到路由参数对应的api：',state.apiName) 
  })

  const rules = reactive({
    title: [
      { required: true, message: '请输入试卷标题', trigger: 'blur' },
      { min: 4, max: 50, message: '长度的合适范围是4-50字', trigger: 'blur' },
    ],
    open_level: [
      {
        required: true,
        message: '请选择公开方式',
        trigger: 'change',
      },
    ],
    publish_time: [
    {  
      required: true,
      message: '选择日期',
      trigger: 'change',
    },
    ],
    grade:[
      {
        required: true,
        message: '请选择年级段',
        trigger: 'change',
      }
    ],
    is_joint:[
      {
        required: true,
        message: '请选择类型',
        trigger: 'change',
      }
    ],
  })
  //检查所有题目的知识点是否都已经关联
  const verifyKnowledgepointLinkQuestion=(questionList)=>{
    let flag=true
    let index=-1
    for(let i=0;i<questionList.length;i++){
      if (questionList[i].knowledgepoint <=0){
        flag=false
        index=i
        break
      }
    }
    return [flag, index]
  }
// 把知识点关联到题目
const linkKnowledgeClick=(knowledgeId,knowledgeName)=>{
  // console.log('知识点选中：',knowledgeId)
  if(state.selectIndex>=0 && knowledgeId>=1){
    if(state.returnQuestionList[state.selectIndex].knowledgepoint.includes(knowledgeId)){
      ElMessage.success("不可重复选择该知识点")
      return 0
    }
    state.returnQuestionList[state.selectIndex].knowledgepoint.push(knowledgeId)
    state.returnQuestionList[state.selectIndex].knowledgepoint_cn.push(knowledgeName)
    // state.returnQuestionList[state.selectIndex].knowledgepoint_cn=knowledgeName
    ElMessage.success("关联知识点成功！")
    console.log('试题关联值守点后：',state.returnQuestionList)
    return true
  }else
  if(state.selectIndex<0){
    ElMessage.error("关联知识点失败，请先选择题目")
    return false;
  }else
  if(knowledgeId<1){
    ElMessage.error("关联知识点失败，请先选择正确的知识点")
    return false;
  }
  else{
    ElMessage.error("关联知识点失败")
    return false;
  }
}
// 选中学科获取知识点
const handleCommand=(command=1)=>{
    command = parseInt(command)
    state.subjectId = command
    state.paperInformation.subject = state.subjectId
    // console.log("下拉设置学科",state.subjectId)
    getKnowledgepointBySubject()
    showKnowledgepointList.value = true
}

  // 选中卡片点击事件
  const selectCardClick=(index)=>{
    // console.log("选中题目索引：",index)
    state.selectIndex = index
  }

  // 获取学科的知识点
  const getKnowledgepointBySubject=()=>{
    if(state.subjectId<1){
      ElMessage.error('先选择学科，再获取');
      return false;
    }
    let params={
      pk:state.subjectId,
    }
    console.log("我要获取知识点了：",state.subjectId)
    axios.get('/GetKnowledgepointBySubjectApiView/',{params}).then(res => {
      console.log("获取知识点结果：",res)
      if (res.code==200){
        ElMessage.success('恭喜，获取知识点成功')
        state.knowledgepointList = deepClone(res.data.results)
        return true
      }else
      if(res.code==1099){
        ElMessage.error('参数错误，获取失败')
        return false
      }else{
        ElMessage.error('服务器错误')
      } 
    })
    .catch((error)=>{
      console.log("error:", error)
    })   
  }
   //检测试卷名称是否重名
   const VerifyPaperTitle=()=>{
      axios.get('/VerifyPaperName/',{params:{paper_title:state.paperInformation.title}}).then(res => {
      if (res.code==200){
        ElMessage.success('恭喜，该标题可以使用^_^')
        return true
      }else{
        ElMessage.error('sorry，该标题已被使用*_*,请更换新标题')
        return false
      }        
    }).catch((error)=>{
      console.log("error:", error)
    })   
  }
 // 上传word文件成功
 const handleSuccess=(response)=> {
  console.log("上传返回数据：",response)
    if(response.code==200){ 
      console.log("上传文件后的题目：", response)
      ElMessage.success("获取所有题目成功！")
      state.returnQuestionList = deepClone(response.data.results.question_list)
      state.paperInformation = deepClone(response.data.results.paper_info)
      let { importQuestionType } = route.query
      if(state.paperInformation && importQuestionType==='importQuestionsAndPaper'){
        state.paperInforVisible=true;
      }
      state.selectedQuestion = deepClone(state.returnQuestionList[0])
      state.buttonDisabeled = false
    }else
    if(response.code==201){
      ElMessage.warning("只获取部分题目")
      state.returnQuestionList = deepClone(response.data.results.question_list)
      let { importQuestionType } = route.query
      if(state.paperInformation && importQuestionType==='importQuestionsAndPaper'){
        state.paperInforVisible=true;
      }
      state.selectedQuestion = deepClone(state.returnQuestionList[0])
      state.buttonDisabeled = false
      ElMessageBox.alert(
        response.message,
        '请检查试卷格式！',
        {
          dangerouslyUseHTMLString: true,
        }
      )
    }else{
      ElMessage.warning("请检查试卷")
      ElMessageBox.alert(
        response.message,
        '请检查试卷格式！',
        {
          dangerouslyUseHTMLString: true,
        }
      )
      // ElMessage.warning(response.message)
    }
  }
  // 上传失败处理
  const handleError=(response)=>{
    console.log("上传文件失败：", response)
  }
  // 开关切换事件
  const handleSwithChange=()=>{
    console.log("开关切换了", state.paperInformation.is_joint)
  }
  //编辑题目
  const editeOneQuestionClick = (question,index)=>{
    // store.commit("setQuestion", question)
    // store.commit("setIndex",index)
    // state.type="edit"
    // state.selectedQuestion = question
    editeOneQuestionDialoge.value.open(index,question)
  }
  // 增加一个空白的题目
  const addOneQuestionClick=(question_item, index)=>{
    let question_new = deepClone(question_item)
    question_new.content_front="待修改"
    question_new.answer_front="待修改"
    question_new.explain_front="待修改"
    question_new.order = index + 1
    state.returnQuestionList.splice(index+1,0,question_new)
  }
  // 当前位置删除一个题目
  const deleteOneQuestionClick=(index)=>{
    state.returnQuestionList.splice(index,1)
  }
  //从store中恢复题目
  const recoverQuestionList =()=>{
    const questionListIndex = store.state.index
    state.returnQuestionList[questionListIndex]=store.state.question
  }
  // 下载模板文档docx
  const DownloadFile=()=>{
    axios({
      url: '/PaperFormatDownLoadView/',
      method: 'GET',
      responseType: 'blob'
    }).then(response => {
      console.log("文件下载：",response)
      const url = window.URL.createObjectURL(new Blob([response]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'file.docx');
      // link.style.display = 'none';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(a)
    }).catch(error => {
      console.log(error);
    });
  }
  // 显示抽屉
  const showHelpDocument=()=>{
    state.showDrawer = true
  }
  // 初始化数据
  const initQuestion=()=>{
    state.returnQuestionList=[];
    state.paperId=0;
    state.importType='';
  }

  // 调整试题列表，去掉无关项
  const reformatQuestionList=(q_list)=>{    
    let deleteList=["answer_front", "content_front","explain_front","images","images_answer","images_explain","knowledgepoint_cn","type_cn","grade"]
    let uploadQuestionList=deepClone(q_list)
    for(let item of uploadQuestionList){
      item=convertQuestionFormat(item)
      item=deleteQuestionItem(item,deleteList)
    }
    return uploadQuestionList
  }
  // 提交到数据库
  const commitClick=()=>{ 
    // 先检测是否所有题目都关联知识点
    let [ flag,index ]=verifyKnowledgepointLinkQuestion(state.returnQuestionList)
    index++;
    let s='第'+index.toString()+'题未关联知识点！'
    if (flag==false){
      ElMessage.error(s)
      return false
    }
    // 调整所有题目的格式
    // let uploadQuestionListTemp=reformatQuestionList(state.returnQuestionList)
    let uploadQuestionListTemp=state.returnQuestionList
    if (state.paperInformation.is_joint === 'true'){
      state.paperInformation.is_joint = true
    }else{
      if(state.paperInformation.is_joint === 'false'){
        state.paperInformation.is_joint = false
      }
    }
    let uploadQuestionList = []
    for(let i=0;i<uploadQuestionListTemp.length;i++){
      uploadQuestionList.push({
        content:uploadQuestionListTemp[i].content,
        answer:uploadQuestionListTemp[i].answer,
        explain:uploadQuestionListTemp[i].explain,
        // pictures:uploadQuestionListTemp[i].pictures,
        // pictures_answer:uploadQuestionListTemp[i].pictures_answer,
        // pictures_explain:uploadQuestionListTemp[i].pictures_explain,
        // content_table:uploadQuestionListTemp[i].content_table,
        // answer_table:uploadQuestionListTemp[i].answer_table,
        // explain_table:uploadQuestionListTemp[i].explain_table,
        knowledgepoint:uploadQuestionListTemp[i].knowledgepoint,
        reference:uploadQuestionListTemp[i].reference,
        type:uploadQuestionListTemp[i].type,
        order:uploadQuestionListTemp[i].order,
        difficulty_level:uploadQuestionListTemp[i].difficulty_level
      })
    }
    let params={
      questionList:uploadQuestionList,
      type:state.importType,
      id:state.paperId,
      paperInformation:state.paperInformation,
    }
    console.log("要提交到数据库的api:",state.apiName)
    console.log('参数为2024-4-21：', params)
    // 发送给后端api，api的名在onmount中确定，根据路由参数type
    state.buttonDisabeled = true;
    state.loading=true;
    axios.post(state.apiName, params).then((result) => {
      state.loading=false;
      state.buttonDisabeled=false;
      console.log("服务器返回提交结果：", result)
      if(result.code==200){
        ElMessage.success( '题目提交成功,去个人中心查看发布结果！')          
        var r=confirm("上传成功。是否去个人中心？");
            if (r==true){
                router.push("/userCenter/myCreatePaper")
            }else{
              initQuestion()
            }
      }else
      if(result.code==201){        
        ElMessage.error( '题目提交成功，申请上线失败，请联系管理员!')
        var r=confirm("上传成功。是否去个人中心？");
            if (r==true){
                router.push("/userCenter/myCreatePaper")
            }else{
              initQuestion()
            }
      }else{
        ElMessage.error( '提交错误，请联系管理员!') 
      }
    })  
    .catch((error)=>{
      console.log("发送错误：", error)
    })  

  }
</script>
<style scoped>
.active {
  background-color:#ffffff!important;
  border: 1px solid #409EFF;
}
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 10px;
    margin: 0;
    padding: 0;
    height: 10px;
  }
  .box-card {
    height:auto;
    overflow-y: auto;
  }
  .line-break{
  white-space: pre-wrap;
  }
  .block{
    display:block;
    width:  150px;
    height: 100px;
  }
  .inlineImage{
    display: inline;
    width:  150px;
    height: 100px;
  }
.affix{
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: right;
    text-align: right;
}
.knowledgepointList{
  padding: 0rpx;
  margin: 0rpx;
  width: 900px;
  display: flex;
  flex-flow: row wrap;
  justify-content:left;
  align-items:flex-start; 
  background-color: rgb(228, 236, 239);
}
.body{
  width: 900px;
  display: flex;
  flex-flow: column nowrap;
  justify-content: left;
  align-items: flex-start; 
}
.download{
  display: flex;
  flex-flow: column nowrap;
  justify-content: space-between;
  align-items: flex-start; 
}
.downloadHeader{
  display: flex;
  flex-flow: row nowrap;
}
</style>